﻿/// <reference path="../interfaces/IUserCredentials.ts" />
/// <reference path="../interfaces/IAccountFactory.ts" />
/// <reference path="../interfaces/IUserInfo.ts" />
/// <reference path="../../../../typings/jquery/jquery.d.ts" />
/// <reference path="../../../../typings/signalr/signalr.d.ts" />

interface IScope extends ng.IScope {
    login: () => void;
    usercredentials: IUserCredentials;
    loginForm: any;
    forgotPassword: () => void;
    changePassword: () => void;
    error: string;
    minimumLength: () => boolean;
    hasCapital: () => boolean;
    hasNumber: () => boolean;
    passwordMatch: () => boolean;
    invalidCharacters: () => boolean;
    changePasswordForm: any;
    $$autocomplete: any;
    reevaluateCredentials: any;
}

class Account {
    constructor($q, $timeout,private $scope: IScope, $routeParams, $location, $rootScope, accountFactory: IAccountFactory, notificationFactory: INotificationFactory, staticObjects: IStaticObjects, userInfoFactory: IUserInfoFactory) {
        var s = $scope;
        var params = $routeParams;
        var init = () => {
            s.usercredentials = { errorMessage: '', password: '', username: $routeParams.user, confirmPassword: '', forgotPasswordEmail: '', rememberMe: true };
            var loginParams = "grant_type=password" +
                "&username=" + $routeParams.user +
                "&password=" + $routeParams.tempKey +
                "&client_id=clientId1" +
                "&client_secret=secret1";
            accountFactory.login(loginParams).success((authData: IAuthData) => {
                if (!authData.access_token || !authData.expires_in || !authData.refresh_token) {
                    notificationFactory.error("", "Login failed!");
                } else {
                    s.usercredentials.errorMessage = "";
                    authData.loginTime = new Date();
                    $rootScope.authData = authData;
                    var refreshToken = { refreshToken: authData.refresh_token, expirationToken: 0 };
                    var date = new Date();
                    date.setTime(new Date().getTime() + (7 * 24 * 60 * 60 * 1000));
                    refreshToken.expirationToken = date.getTime();
                    localStorage.setItem('sust_refresh_token', JSON.stringify(refreshToken));
                    window.setTimeout(accountFactory.refreshToken, (authData.expires_in - 5) * 1000);
                }
            }).error((data, status, headers, config, statusText) => {
                localStorage.removeItem('sust_refresh_token');
                localStorage.removeItem('sust:a:ur');
                    staticObjects.clearUserInfo();
                    if (data != undefined && data.error == "login_error_code")
                    {
                        var code = parseInt(data.error_description);
                        s.usercredentials.errorMessage = staticObjects.getErrorMesageByStatusCode(500, { code: code });
                        if (code == 1007)
                            staticObjects.redirectToLink('/passwordExpired');
                        if (code == 1004)
                            staticObjects.redirectToDefault();
                    }
                    else
                        s.usercredentials.errorMessage = data.error_description;
                });
        };
        if ($routeParams != undefined && $routeParams.tempKey != undefined && $routeParams.user != undefined) {
            $.when(init());
        }
        $scope.$watch('usercredentials.username', function () {
            if (!s.usercredentials)
                return;

            if (s.usercredentials.autoComplete)
                s.usercredentials.errorMessage = "";

            if (s.usercredentials.autoComplete) {
                s.usercredentials.autoComplete = s.usercredentials.autoComplete - 1;
            }
        });
        $scope.$watch('usercredentials.password', function () {
            if (!s.usercredentials)
                return;
            if (!s.usercredentials.autoComplete)
                s.usercredentials.errorMessage = "";

            if (s.usercredentials.autoComplete) {
                s.usercredentials.autoComplete = s.usercredentials.autoComplete - 1;
            }
        });

        $scope.reevaluateCredentials = function (resetMessage) {

            if ($scope.$$autocomplete) {

                var email = $scope.$$autocomplete.getEmail();
                if ($scope.usercredentials.username || email) {
                    if ($scope.usercredentials.username !== email) {
                        $scope.usercredentials.autoComplete = (s.usercredentials.autoComplete || 0) + 1;
                        $scope.usercredentials.username = email;
                        if (resetMessage) {
                            s.usercredentials.errorMessage = "";
                        }
                    }
                }

                var password = $scope.$$autocomplete.getPassword();
                if ($scope.usercredentials.password || password) {
                    if ($scope.usercredentials.password !== password) {
                        $scope.usercredentials.autoComplete = (s.usercredentials.autoComplete || 0) + 1;
                        $scope.usercredentials.password = password;
                        if (resetMessage) {
                            s.usercredentials.errorMessage = "";
                        }
                    }
                }

            }
        };

        s.login = () => {
            s.usercredentials.errorMessage = "";
            s.reevaluateCredentials(false);

            var emailRegularExpression = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
            var emailTest = emailRegularExpression.test($scope.usercredentials.username);
            if (!emailTest) {
                s.usercredentials.errorMessage = "Please enter a valid email address.";
                return;
            }

            s.usercredentials.errorMessage = "";
            var loginParams = "grant_type=password" +
                "&username=" + $scope.usercredentials.username +
                "&password=" + $scope.usercredentials.password +
                "&client_id=clientId1" +
                "&client_secret=secret1";
            accountFactory.login(loginParams).success((authData: IAuthData) => {
                if (!authData.access_token || !authData.expires_in || !authData.refresh_token) {
                    notificationFactory.error("", "Login failed!");
                } else {
                    s.usercredentials.errorMessage = "";
                    authData.loginTime = new Date();
                    $rootScope.authData = authData;
                    var refreshToken = { refreshToken: authData.refresh_token, expirationToken: 0 };
                    if (s.usercredentials.rememberMe) {
                        var date = new Date();
                        date.setTime(new Date().getTime() + (7 * 24 * 60 * 60 * 1000));
                        refreshToken.expirationToken = date.getTime();
                    }

                    localStorage.setItem('sust_refresh_token', JSON.stringify(refreshToken));
                    window.setTimeout(accountFactory.refreshToken, (authData.expires_in - 5) * 1000);
                    $.when(accountFactory.profile().success((userInfo: IUserInfo) => {
                        $rootScope.userInfo = userInfo;
                        localStorage.setItem('sust_userInfo', JSON.stringify($rootScope.userInfo));
                        // get ui resources
                        accountFactory.permissions();
                        // ga.create('UA-56430676-1', { 'userId': $rootScope.userInfo.userId });

                        // send user ID to Google Analytics trackers
                        ga('create', 'UA-56430676-1', 'auto', { 'userId': $rootScope.userInfo.userId });
                        ga('set', 'dimension1', $rootScope.userInfo.userId);
                        ga('send', 'pageview');
                        
                            //if (userInfo.isAuthenticated)
                                //staticObjects.initSignalR();
                        }).error(staticObjects.errorCallback))
                        .done(() => {
                            staticObjects.redirectToDefault();
                        });

               
                }
            }).error((data, status, headers, config, statusText) => {
                if (data != undefined && data.error == "login_error_code")
                    s.usercredentials.errorMessage = staticObjects.getErrorMesageByStatusCode(500, { code: parseInt(data.error_description) });
                else
                    s.usercredentials.errorMessage = data.error_description;
                //notificationFactory.error("", "Login failed!");
            });
        };
        s.forgotPassword = () => {
            var emailRegularExpression = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
            var emailTest = emailRegularExpression.test($scope.usercredentials.forgotPasswordEmail);
            if (!emailTest) {
                s.usercredentials.errorMessage = "Please enter a valid email address.";
                return;
            }

            accountFactory.forgotPassword('"' + $scope.usercredentials.forgotPasswordEmail + '"').success(() => {
                s.usercredentials.errorMessage = "";
                staticObjects.redirectToLink("/forgotPasswordConfirmation");
            }).error((data, status, headers, config, statusText) => {
                s.usercredentials.errorMessage = staticObjects.getErrorMesageByStatusCode(status, data);
                });
        };
        s.changePassword = () => {
            var changePassword: IChangePassword = { username: $scope.usercredentials.username, password: $scope.usercredentials.password };
            accountFactory.changePassword(changePassword).success(() => {
                s.usercredentials.errorMessage = "";
                $.when(accountFactory.profile().success((userInfo: IUserInfo) => {
                    $rootScope.userInfo = userInfo;
                }).error(staticObjects.errorCallback))
                    .done(() => {
                        staticObjects.redirectToDefault();
                    });
                }).error((data, status, headers, config, statusText) => {
                    s.usercredentials.errorMessage = staticObjects.getErrorMesageByStatusCode(status, data);
                });
        };
        s.minimumLength = function () {
            s.changePasswordForm.passwordBox.$setValidity("PasswordLength", s.usercredentials.password.length > 6);
            return s.usercredentials.password.length > 6;
        };
        s.hasCapital = function () {
            var regexp = /(?=.*[A-Z])/;
            s.changePasswordForm.passwordBox.$setValidity("PasswordDoesNotHaveCapital", regexp.test(s.usercredentials.password));
            return regexp.test(s.usercredentials.password);
        };
        s.hasNumber = function () {
            var regexp = /(?=.*[0-9])/;
            s.changePasswordForm.passwordBox.$setValidity("PasswordDoesNotHaveNumber", regexp.test(s.usercredentials.password));
            return regexp.test(s.usercredentials.password);
        };
        s.passwordMatch = function () {
            s.changePasswordForm.passwordBox.$setValidity("PasswordDoesNotMatch", s.usercredentials.password == s.usercredentials.confirmPassword);
            return s.usercredentials.password == s.usercredentials.confirmPassword && s.usercredentials.password.length > 0
        };
        s.invalidCharacters = function () {
            var regexp = /(^.*?(?=[&'"<>}]).*$)/;
            s.changePasswordForm.passwordBox.$setValidity("PasswordHasInvalidCharacter", !regexp.test(s.usercredentials.password));
            return regexp.test(s.usercredentials.password);
        };
        var activateSignalR = () => {
            $.connection.hub.start().done(() => {
            }).fail(error => {
                alert(error.message);
            });
        };
    }
}
angular.module('shell').controller('Account', ['$q', '$timeout', '$scope', '$routeParams', '$location', '$rootScope', 'accountFactory', 'notificationFactory', 'staticObjects', 'userInfoFactory', ($q, $timeout, $scope, $routeParams, $location, $rootScope, accountFactory, notificationFactory, staticObjects, userInfoFactory) =>
    new Account($q, $timeout,$scope, $routeParams, $location, $rootScope, accountFactory, notificationFactory, staticObjects, userInfoFactory)
]);
 